package live.zs.quarkus;

import org.apache.commons.io.FileUtils;
import org.eclipse.microprofile.config.inject.ConfigProperty;
import org.eclipse.microprofile.rest.client.inject.RestClient;
import org.jboss.resteasy.annotations.providers.multipart.MultipartForm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.inject.Inject;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.File;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Arrays;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author madison
 * @description
 * @date 2022/5/2 09:28
 */
@Path("/client")
public class MultipartClientResource {
    private static final Logger logger = LoggerFactory.getLogger(MultipartClientResource.class);

    @Inject
    @RestClient
    MultipartService service;

    @ConfigProperty(name = "local.file.name")
    Optional<String> localFileName;

    @ConfigProperty(name = "file.name", defaultValue = "upload")
    Optional<String> limitFileName;

    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String hello() {
        return "Hello quarkus file name: " + limitFileName;
    }

    @POST
    @Path("/multipart")
    @Produces(MediaType.TEXT_PLAIN)
    public Response sendFile(@MultipartForm MultipartBody data, @HeaderParam("file") String file) throws Exception {
//        MultipartBody body = new MultipartBody();
//        body.fileName = "greeting.txt";
//        body.file = new ByteArrayInputStream("HELLO WORLD".getBytes(StandardCharsets.UTF_8));

        InputStream i = data.file.getBody(InputStream.class, null);

//        logger.info("file name:{}", data.fileName);
//        logger.info("file content:{}", new String(is.readAllBytes()));

        String[] contentDisposition = data.file.getHeaders().getFirst("Content-Disposition").split(";");
        String fileName = "";
        for (String filename : contentDisposition) {
            if ((filename.trim().startsWith("filename"))) {
                String[] name = filename.split("=");
                fileName = name[1].trim().replaceAll("\"", "");
            }
        }
        logger.info("file name:{}", fileName);
        logger.info("header path file:{}", file);
        logger.info("limit file name:{}", limitFileName);

        File localConfigFile = FileUtils.getFile("files.config");
        logger.info("config file: {}", localConfigFile.getAbsoluteFile());

        String localFileConfigContent = Files.readString(Paths.get(localFileName.get()));
        logger.info("config file content:{}", localFileConfigContent);

        if (Objects.nonNull(localFileConfigContent) && !localFileConfigContent.isBlank() &&
                Arrays.stream(localFileConfigContent.split(",")).collect(Collectors.toList()).contains(fileName)) {
            File newFile = FileUtils.getFile(LocalDateTime.now().toEpochSecond(ZoneOffset.UTC) + "-" + fileName);
            FileUtils.copyToFile(i, newFile);
            return Response.ok("download success").build();
        } else {
            return Response.ok("file error").build();
        }

//        if ((Objects.nonNull(file) && Arrays.stream(file.split(",")).collect(Collectors.toList()).contains(fileName))
//                || (limitFileName.isPresent() && Arrays.stream(limitFileName.get().split(",")).collect(Collectors.toList()).contains(fileName))) {
//            File newFile = FileUtils.getFile(LocalDateTime.now().toEpochSecond(ZoneOffset.UTC) + fileName);
//            FileUtils.copyToFile(i, newFile);
//
//            return Response.ok("download success!").build();
////        return service.sendMultipartData(data);
//        } else {
//            return Response.ok("file error").build();
//        }
    }
}
